package top.ywlog.permission.service;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.dao.SysAclMapper;
import top.ywlog.permission.dao.SysRoleAclMapper;
import top.ywlog.permission.dao.SysRoleUserMapper;
import top.ywlog.permission.model.SysAcl;
import top.ywlog.permission.model.SysUser;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Durian
 * @date: 2020/10/28 20:55
 * @description: 获取用户和角色的权限
 */
@Service
public class SysCoreService
{

    @Resource
    private SysAclMapper sysAclMapper;
    @Resource
    private SysRoleAclMapper sysRoleAclMapper;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    List<SysAcl> getCurrentUserAclList()
    {
        Integer userId = RequestHolder.getCurrentUser().getId();
        return getUserAclList(userId);
    }

    List<SysAcl> getRoleAclList(int roleId)
    {
        List<Integer> aclIdList = sysRoleAclMapper.getAclIdListByRoleIdList(Lists.newArrayList(roleId));
        if (CollectionUtils.isEmpty(aclIdList))
        {
            return Lists.newArrayList();
        }
        return sysAclMapper.getByIdList(aclIdList);
    }


    private List<SysAcl> getUserAclList(Integer userId)
    {
        if (isSuperAdmin())
        {
            // 获取所有权限
            sysAclMapper.getAll();
        }
        // 根据用户id查询拥有的角色id
        List<Integer> roleIdList = sysRoleUserMapper.getRoleIdListByUserId(userId);
        if (CollectionUtils.isEmpty(roleIdList))
        {
            return Lists.newArrayList();
        }
        // 根据角色id列表查询所有权限id列表
        List<Integer> idList = sysRoleAclMapper.getAclIdListByRoleIdList(roleIdList);
        if (CollectionUtils.isEmpty(idList))
        {
            return Lists.newArrayList();
        }
        return sysAclMapper.getByIdList(idList);
    }

    private boolean isSuperAdmin()
    {
        // 定义了一个假的超级管理员规则，实际中要根据项目进行修改
        // 可以是配置文件获取，可以指定某个用户，也可以指定某个角色
        SysUser sysUser = RequestHolder.getCurrentUser();
        return sysUser.getMail().contains("admin");
    }

}
